#!/bin/sh

# Docker入口脚本 - 用于前端容器启动时的初始化

set -e

# 函数：等待后端服务就绪
wait_for_backend() {
    echo "等待后端服务启动..."
    until curl -f http://dataworks-backend:8000/api/health >/dev/null 2>&1; do
        echo "后端服务未就绪，等待5秒后重试..."
        sleep 5
    done
    echo "后端服务已就绪!"
}

# 函数：健康检查
health_check() {
    # 检查nginx进程
    if ! pgrep nginx > /dev/null; then
        echo "Nginx进程未运行"
        exit 1
    fi
    
    # 检查nginx配置
    if ! nginx -t > /dev/null 2>&1; then
        echo "Nginx配置错误"
        exit 1
    fi
    
    # 检查静态文件
    if [ ! -f "/usr/share/nginx/html/index.html" ]; then
        echo "静态文件缺失"
        exit 1
    fi
    
    echo "健康检查通过"
    return 0
}

# 主逻辑
case "$1" in
    "nginx")
        echo "启动前端服务..."
        
        # 可选：等待后端服务（如果需要）
        if [ "${WAIT_FOR_BACKEND}" = "true" ]; then
            wait_for_backend
        fi
        
        # 启动nginx
        echo "启动 Nginx..."
        exec nginx -g "daemon off;"
        ;;
        
    "health")
        health_check
        ;;
        
    *)
        # 默认执行传入的命令
        exec "$@"
        ;;
esac 